// 云函数入口文件
const cloud = require('wx-server-sdk')
const md5 = require('md5-node')

cloud.init()


const db = cloud.database();
const collectTable = db.collection('gas_collect');
const _ = db.command;
const $ = db.command.aggregate

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  try {
    if(event.stationId){//查询是否已经被当前用户收藏
      return await collectTable.where({
        '_id': _.eq(md5(wxContext.OPENID)),
        'gasList': event.stationId
      }).get();
    } else { //查询当前用户的所有收藏加油站
      const countResult = await collectTable.count()
      const total = countResult.total
      const res = total ? await collectTable.aggregate().match({
        '_id': _.eq(md5(wxContext.OPENID))
      }).lookup({
        from: 'stations',
        localField: 'gasList',
        foreignField: '_id',
        as: 'stationList'
      }).end(): null


      if (res) {//存在收藏
        return {
          msg: '查询成功',
          rows: res.list
        }          
        
      } else {
        return {
          code:200,
          msg:'暂时没有关注',
          rows:[]
        }
      }

    }
  } catch (err) {
    console.error(err)
  }
}